//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.Controls;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using ResourceControl = CommunityServer.ControlPanel.Controls.ResourceControl;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;
using System.Text.RegularExpressions;

namespace CommunityServer.ControlPanel.Tools
{
	/// <summary>
	/// Summary description for ExceptionsReport.
	/// </summary>
	public class ExceptionsReport : BaseToolsPage
	{
		public static Regex getCaseChanges = new Regex("([a-z][A-Z])", RegexOptions.Compiled);

		#region Members

		protected DropDownList ExceptionType;
		protected DropDownList MinFrequency;
		protected DropDownList SortBy;
		protected CheckBox IncludeUnknown;
		protected Repeater ReportRepeater;
		protected IButton SelectDomain;
		protected CommunityServer.ControlPanel.Controls.ResourceButton DeleteAll;
		protected CommunityServer.ControlPanel.Controls.ResourceButton DeleteSelected;

		ReportsViewMode reportMode = ReportsViewMode.AllExceptions;
		#endregion

		override protected void OnInit(EventArgs e)
		{
			ReportRepeater.ItemDataBound += new RepeaterItemEventHandler(this.ReportRepeater_ItemDataBound);
			SelectDomain.Click += new EventHandler(ChangeApplication_Click);
			DeleteAll.Click += new EventHandler(DeleteAll_Click);
			DeleteSelected.Click += new EventHandler(DeleteSelected_Click);
			this.Load += new EventHandler(this.Page_Load);

			base.OnInit(e);
		}


		private void Page_Load(object sender, EventArgs e)
		{
			if (!this.IsPostBack)
			{
				this.Bind();
			}
		}

		public string GetDisplayName(string text)
		{
			foreach (Match m in getCaseChanges.Matches(text))
			{
				text = text.Replace(m.Groups[1].Value, m.Groups[1].Value.Substring(0, 1) + " " + m.Groups[1].Value.Substring(1));
			}

			return text;
		}

		protected void Bind()
		{

			  
			switch (reportMode)
			{
				default:
					if (ExceptionType != null && !IsPostBack)
					{
						ExceptionType.Items.Add( new ListItem( Components.ResourceManager.GetString( "CP_Tools_ExceptionsReport_AllExceptions" ), "-1" ) );

						// Populate the filter
						ArrayList types = new ArrayList();
						foreach (CSExceptionType type in Enum.GetValues(typeof(CSExceptionType)))
						{
							types.Add(type.ToString());
						}

						types.Sort();

						foreach (string type in types)
						{
							ExceptionType.Items.Add(new ListItem(GetDisplayName(type), ((int) Enum.Parse(typeof(CSExceptionType), type)).ToString()));
						}
					}
                    
					if (MinFrequency != null &&	!Page.IsPostBack)
					{
						MinFrequency.Items.Add( new ListItem( Components.ResourceManager.GetString( "CP_Tools_ExceptionsReport_MinFrequency_0" ), "0" ) );
						MinFrequency.Items.Add( new ListItem( Components.ResourceManager.GetString( "CP_Tools_ExceptionsReport_MinFrequency_10" ), "10" ) );
						MinFrequency.Items.Add( new ListItem( Components.ResourceManager.GetString( "CP_Tools_ExceptionsReport_MinFrequency_25" ), "25" ) );
						MinFrequency.Items.Add( new ListItem( Components.ResourceManager.GetString( "CP_Tools_ExceptionsReport_MinFrequency_100" ), "100" ) );
						MinFrequency.Items.Add( new ListItem( ResourceManager.GetString( "CP_Tools_ExceptionsReport_MinFrequency_1000" ), "1000" ) );
					}

					if (SortBy != null && !Page.IsPostBack)
					{
						SortBy.Items.Add(new ListItem(Components.ResourceManager.GetString("CP_Tools_ExceptionsReport_SortBy_Frequency"), ((int)SortExceptionsBy.Frequency).ToString()));
						SortBy.Items.Add(new ListItem(Components.ResourceManager.GetString("CP_Tools_ExceptionsReport_SortBy_Date"), ((int)SortExceptionsBy.LastOccurred).ToString()));
					}

					if (ReportRepeater != null)
						ReportRepeater.DataSource = CSException.GetExceptions( int.Parse(ExceptionType.SelectedValue), int.Parse(MinFrequency.SelectedValue), int.Parse(SortBy.SelectedValue), IncludeUnknown.Checked);

					break;
			}

			if (((ArrayList) ReportRepeater.DataSource).Count > 0) 
			{
				ReportRepeater.Visible = true;
				ReportRepeater.DataBind();
			} 
			else 
			{
				ReportRepeater.Visible = false;
			}

		}

		#region Properties

		/// <value>
		/// Controls the mode that the thread view control displays
		/// </value>
		public ReportsViewMode ReportMode 
		{
			get { return reportMode; }
			set { reportMode = value; }
		}

		#endregion

		#region Event Handlers

		private void ReportRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
			{
				CSException ex = e.Item.DataItem as CSException;
				if (ex != null)
				{

					CheckBox BulkEdit = e.Item.FindControl("BulkEdit") as CheckBox;
					if (BulkEdit != null)
						BulkEdit.Checked = false;

					Literal ExceptionID = e.Item.FindControl("ExceptionID") as Literal;
					if (ExceptionID != null)
						ExceptionID.Text = ex.ExceptionID.ToString();

					Literal UserAgent = e.Item.FindControl("UserAgent") as Literal;
					if (UserAgent != null)
						UserAgent.Text = Server.HtmlEncode(ex.UserAgent);

					Literal Path = e.Item.FindControl("Path") as Literal;
					if (Path != null)
						Path.Text = Server.HtmlEncode(ex.HttpPathAndQuery);

					Literal HttpVerb = e.Item.FindControl("HttpVerb") as Literal;
					if (HttpVerb != null)
						HttpVerb.Text = Server.HtmlEncode(ex.HttpVerb);

					Literal HttpReferrer = e.Item.FindControl("HttpReferrer") as Literal;
					if (HttpReferrer != null)
						HttpReferrer.Text = Server.HtmlEncode(ex.HttpReferrer);
					
					Literal _Message = e.Item.FindControl("Message") as Literal;
                    if (_Message != null)
                        _Message.Text = Server.HtmlEncode(ex.Message);
					
					Literal LoggedStackTrace = e.Item.FindControl("LoggedStackTrace") as Literal;
					if (LoggedStackTrace != null)
                        LoggedStackTrace.Text = Server.HtmlEncode(ex.LoggedStackTrace).Replace(Environment.NewLine, "<br />");

					Literal _ExceptionType = e.Item.FindControl("ExceptionType") as Literal;
                    if (_ExceptionType != null)
                        _ExceptionType.Text = ex.ExceptionType.ToString();

					Literal IPAddress = e.Item.FindControl("IPAddress") as Literal;
					if (IPAddress != null)
						IPAddress.Text = Server.HtmlEncode(ex.IPAddress);

					Literal DateLastOccurred = e.Item.FindControl("DateLastOccurred") as Literal;
					if (DateLastOccurred != null)
						DateLastOccurred.Text = ex.DateLastOccurred.ToString();

					Literal Frequency = e.Item.FindControl("Frequency") as Literal;
					if (Frequency != null)
						Frequency.Text = ex.Frequency.ToString();

				}
			}
		}



		public void ChangeApplication_Click(object sender, EventArgs e) 
		{
			Bind();
		}

		public void DeleteAll_Click(object sender, EventArgs e) 
		{
			CSException.DeleteExceptions(CSContext.Current.SiteSettings.SettingsID, null);
			Bind();
		}

		public void DeleteSelected_Click(object sender, EventArgs e) 
		{
			ArrayList deleteList = new ArrayList();
			foreach (RepeaterItem i in ReportRepeater.Items) 
			{
				CheckBox c = i.FindControl("BulkEdit") as CheckBox;

				if ((c != null) && (c.Checked))
				{
					Literal l = i.FindControl("ExceptionID") as Literal;
					if (l != null)
						deleteList.Add( int.Parse(l.Text) );
				}
			}

			CSException.DeleteExceptions(CSContext.Current.SiteSettings.SettingsID, deleteList);
			Bind();
		}
		
		#endregion


	}
}
